package com.idbk.chargestation.adapter;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.api.APIForPoint;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonComment;
import com.idbk.chargestation.bean.JsonComment.JsonCommentPraiseUser;
import com.idbk.chargestation.bean.JsonReplyResult;
import com.idbk.chargestation.bean.JsonReplysList;
import com.idbk.chargestation.dialog.DialogReplyComment;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.DateUtils;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.NestedListView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * （充电点）评论列表适配器
 *
 * @author liangzw, lupc
 */
public class PointCommentAdapter extends BaseAdapter {

    public final static String TAG = PointCommentAdapter.class.getSimpleName();

    private Context mContext;
    private List<JsonComment> mData;
    private DialogReplyComment mDialog;//评论回复

    private LayoutInflater mInflater;

    private ProgressDialog mProgressDialog;//等待框
    private StringRequest mRequest;//当前请求(配合等待框)

    public PointCommentAdapter(Context context, List<JsonComment> data) {
        mContext = context;

        mInflater = LayoutInflater.from(context);

        mDialog = new DialogReplyComment(context);
        mData = data;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class Holder {
        TextView textName, textDate, textContent;
        ImageView mImageUser;
        ImageView mImageCarLogo, mImagePraise, mImageReply;

        RatingBar mRatingComment;//评分

        LinearLayout mLayoutUserLike;//包含 点赞人的区域
        TextView mTextUserLike;//点赞的人
        View mViewDivideReply;//分割线

        NestedListView mNListView;//回复列表

        View mViewReplyListFoot;
        TextView mTextReplyListFoot;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder hold;
        if (convertView == null) {
            hold = new Holder();
            convertView = mInflater.inflate(R.layout.item_comment, parent, false);

            hold.textName = (TextView) convertView.findViewById(R.id.item_pilecomment_username);
            hold.mImageCarLogo = (ImageView) convertView.findViewById(R.id.item_pilecomment_car_logo);
            hold.textDate = (TextView) convertView.findViewById(R.id.item_pilecomment_date);
            hold.textContent = (TextView) convertView.findViewById(R.id.item_pilecomment_content);
            hold.mImageUser = (ImageView) convertView.findViewById(R.id.item_pilecomment_userphoto);

            hold.mImagePraise = (ImageView) convertView.findViewById(R.id.imageview_comment_like);
            hold.mImageReply = (ImageView) convertView.findViewById(R.id.imageview_replay);

            hold.mRatingComment = (RatingBar) convertView.findViewById(R.id.ratingbar_comment);

            hold.mLayoutUserLike = (LinearLayout) convertView.findViewById(R.id.layout_item_comment_user_like);
            hold.mTextUserLike = (TextView) convertView.findViewById(R.id.textview_item_comment_user_like);
            hold.mViewDivideReply = convertView.findViewById(R.id.view_devide_reply);
            hold.mNListView = (NestedListView) convertView.findViewById(R.id.nestedlistview_replies);

            hold.mViewReplyListFoot = mInflater.inflate(R.layout.item_comment_reply_foot, hold.mNListView, false);
            hold.mTextReplyListFoot = (TextView) hold.mViewReplyListFoot.findViewById(R.id.textview_item_comment_reply_foot);
            hold.mNListView.addFooterView(hold.mViewReplyListFoot);

            convertView.setTag(hold);//缓存组件
        } else {
            hold = (Holder) convertView.getTag();
        }

        bindView(position, hold);

        return convertView;
    }

    private void bindView(final int position, final Holder hold) {
        final JsonComment item = mData.get(position);

        hold.textContent.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                int userId = AppContext.getInstance().getMyUserId();
                String[] strs;
                if (userId == item.userId) {
                    strs = new String[]{"复制", "删除"};
                } else {
                    strs = new String[]{"复制"};
                }
                new AlertDialog.Builder(mContext)
                        .setItems(strs, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    //复制
                                    ClipboardManager cmb = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                                    ClipData clip = ClipData.newPlainText(item.getName(), item.comment);
                                    cmb.setPrimaryClip(clip);
                                    Toast.makeText(mContext, "已复制", Toast.LENGTH_SHORT).show();
                                } else if (which == 1) {
                                    deleteComment(position, item.id);
                                }
                            }

                        })
                        .create()
                        .show();
                return false;
            }
        });

        hold.mImagePraise.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!AppContext.getInstance().isLogin()) {
                    Intent intent = new Intent(mContext, ActivityLogin.class);
                    mContext.startActivity(intent);
                    return;
                }
                if (item.praiseFlag) {
                    //取消点赞
                    mRequest = APIForPoint.undoPointCommentPraise(item.id, new EHttpResponse() {

                        @Override
                        public void onEResponse(String response) {
                            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
                            if (BaseActivity.handleResponseStatus(mContext, result)) {
                                item.praiseFlag = false;
                                //从点赞列表中移除数据
                                if (item.praiseInfos != null) {
                                    int userId = AppContext.getInstance().getMyUserId();
                                    for (int i = 0; i < item.praiseInfos.size(); i++) {
                                        if (item.praiseInfos.get(i).id == userId) {
                                            item.praiseInfos.remove(i);
                                            break;
                                        }
                                    }
                                }
                                updatePraiseInfo(item, hold);
                            }
                        }

                        @Override
                        public void onEErrorResponse(VolleyError error) {
                            Log.e(TAG, error.getMessage(), error.getCause());
                            Toast.makeText(mContext, "点赞失败，请检查你的网络！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onEFinish() {
                            super.onEFinish();
                        }
                    });

                } else {
                    //发送点赞
                    mRequest = APIForPoint.doPointCommentPraise(item.id, new EHttpResponse() {

                        @Override
                        public void onEResponse(String response) {
                            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
                            if (BaseActivity.handleResponseStatus(mContext, result)) {
                                item.praiseFlag = true;
                                //在点赞列表中增加数据
                                if (item.praiseInfos == null) {
                                    item.praiseInfos = new ArrayList<JsonCommentPraiseUser>();
                                }
                                int userId = AppContext.getInstance().getMyUserId();
                                String userName = AppContext.getInstance().getUserNickName();
                                item.praiseInfos.add(new JsonCommentPraiseUser(userId, userName));
                                updatePraiseInfo(item, hold);
                            } else if (result != null && result.status == GlobalResult.POINT_COMMENT_PRAISED.getStatus()) {
                                /* 这种情况下表示用户刚刚登陆，数据没有刷新 */
                                //该评论已经点赞
                                item.praiseFlag = true;
                                //在点赞列表中增加数据
                                int userId = AppContext.getInstance().getMyUserId();
                                String userName = AppContext.getInstance().getUserNickName();
                                if (item.praiseInfos == null) {
                                    item.praiseInfos = new ArrayList<JsonCommentPraiseUser>();
                                    item.praiseInfos.add(new JsonCommentPraiseUser(userId, userName));
                                    updatePraiseInfo(item, hold);
                                } else {
                                    //判断当前列表是否拥有
                                    boolean has = false;
                                    for (int i = 0; i < item.praiseInfos.size(); i++) {
                                        if (item.praiseInfos.get(i).id == userId) {
                                            has = true;
                                            break;
                                        }
                                    }
                                    if (!has) {
                                        item.praiseInfos.add(new JsonCommentPraiseUser(userId, userName));
                                        updatePraiseInfo(item, hold);
                                    }
                                }
                            }
                        }

                        @Override
                        public void onEErrorResponse(VolleyError error) {
                            Log.e(TAG, error.getMessage(), error.getCause());
                            Toast.makeText(mContext, "点赞失败，请检查你的网络！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onEFinish() {
                            super.onEFinish();
                        }

                    });
                }
            }
        });
        hold.mImageReply.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //传入用户名和Id到评论框
                if (!AppContext.getInstance().isLogin()) {
                    Intent intent = new Intent(mContext, ActivityLogin.class);
                    mContext.startActivity(intent);
                    return;
                }
                mDialog.setReplyToComment(item.id, item.userId, item.getName(), true);
                mDialog.setOnReplaySuccessListener(new DialogReplyComment.OnReplaySuccessListener() {

                    @Override
                    public void onReplay(JsonReplyResult result) {
                        item.addReply(result.reply);
                        //刷新回复列表
                        //初始化 回复列表
                        bindReply(item, hold);

                        //检查分割线
                        checkDivideLine(item, hold);
                    }
                });
                mDialog.show();
            }
        });

        bindComment(item, hold);
    }

    private void bindComment(final JsonComment item, final Holder hold) {
        //显示 评论人名称
        hold.textName.setText(item.getName());
        //显示 评论人车主认证-车标
        if (item.carLogos != null && item.carLogos.size() > 0) {
            hold.mImageCarLogo.setImageBitmap(null);
            String url = ChargeStationURL.getRootURL() + item.carLogos.get(0);
            Picasso.with(mContext)
                    .load(url)
                    .into(hold.mImageCarLogo);
        } else {
            hold.mImageCarLogo.setImageBitmap(null);
        }
        //显示评论时间
        hold.textDate.setText(DateUtils.getTimeDifference(item.commentDate));
        //显示评论内容
        hold.textContent.setText(item.comment);
        //显示头像
        String url = ChargeStationURL.getRootURL() + item.imageURL;
        Picasso.with(mContext)
                .load(url)
                .placeholder(R.drawable.ico_preimg_loading)
                .error(R.drawable.ico_me_default_user_pic)
                .fit()
                .into(hold.mImageUser);

        //评分
        hold.mRatingComment.setRating(item.mark);

        //刷新点赞相关的视图
        updatePraiseInfo(item, hold);

        //初始化 回复列表
        bindReply(item, hold);
    }

    private void bindReply(final JsonComment item, final Holder hold) {
        if (item.replys != null && item.replys.size() > 0) {
            hold.mNListView.setVisibility(View.VISIBLE);
            final PointCommentReplyAdapter adapter = new PointCommentReplyAdapter(
                    mContext, item.id, item.replys);
            adapter.setmOnDeleteListener(new PointCommentReplyAdapter.OnDeleteListener() {

                @Override
                public void onDelete(boolean result) {
                    if (result) {
                        checkDivideLine(item, hold);
                    }
                }
            });
            adapter.setmOnAddListener(new PointCommentReplyAdapter.OnAddListener() {

                @Override
                public void onAdd(boolean result) {
                    if (result) {
                        notifyDataSetChanged();
                    }
                }
            });
            //如果一开始的总数小于初始值，则不显示foot
            if (item.replyCount <= JsonComment.PAGE_SIZE_REPLYS) {
                if (hold.mNListView.getFooterViewsCount() > 0) {
                    hold.mNListView.removeFooterView(hold.mViewReplyListFoot);
                }
            } else {
                if (hold.mNListView.getFooterViewsCount() < 1) {
                    hold.mNListView.addFooterView(hold.mViewReplyListFoot);
                }
                //根据总条数和剩余显示数据来决定 foot的视图
                refreshReplyListFoot(adapter, item, hold);
            }
            //
            hold.mNListView.setAdapter(adapter);
        } else {
            hold.mNListView.setVisibility(View.GONE);
        }
    }

    private void checkDivideLine(final JsonComment item, final Holder hold) {
        if (item.praiseInfos != null && item.praiseInfos.size() > 0
                && item.replys != null && item.replys.size() > 0) {
            hold.mViewDivideReply.setVisibility(View.VISIBLE);
        } else {
            hold.mViewDivideReply.setVisibility(View.GONE);
        }
    }

    private void updatePraiseInfo(JsonComment item, Holder hold) {
        if (item.praiseFlag) {
            hold.mImagePraise.setImageResource(R.drawable.btn_map_comment_like);
        } else {
            hold.mImagePraise.setImageResource(R.drawable.btn_map_comment_like_normal);
        }

        if (item.praiseInfos != null && item.praiseInfos.size() > 0) {
            int count = item.praiseInfos.size();
            StringBuilder sb = new StringBuilder();
            if (count > 3) {
                for (int i = 0; i < 3; i++) {
                    sb.append(item.praiseInfos.get(i).getUserName());
                    sb.append("，");
                }
                sb.deleteCharAt(sb.length() - 1);
                sb.append("等").append(count).append("人");
            } else {
                for (int i = 0; i < item.praiseInfos.size(); i++) {
                    sb.append(item.praiseInfos.get(i).getUserName());
                    sb.append("，");
                }
                sb.deleteCharAt(sb.length() - 1);
                if (count > 1) {
                    sb.append("等").append(count).append("人");
                }
            }
            sb.append("觉得很赞");
            hold.mTextUserLike.setText(sb.toString());

            hold.mLayoutUserLike.setVisibility(View.VISIBLE);
        } else {
            hold.mLayoutUserLike.setVisibility(View.GONE);
        }

        //检查分割线
        checkDivideLine(item, hold);
    }

    private void refreshReplyListFoot(
            final PointCommentReplyAdapter adapter,
            final JsonComment item,
            final Holder hold
    ) {
        //根据剩余回复数来
        if (item.getRemainReplys() > 0) {
            hold.mTextReplyListFoot.setText("加载更多");
            hold.mTextReplyListFoot.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    showProgressDialog();
                    final int pageIndex = item.mPageIndex + 1;
                    Log.d(TAG, "评论id:" + item.id + " 页码：" + pageIndex);
                    mRequest = APIForPoint.getPointCommentReplys(item.id, pageIndex, JsonComment.PAGE_SIZE_REPLYS, new EHttpResponse() {

                        @Override
                        public void onEResponse(String response) {
                            JsonReplysList result = GsonUtils.toBean(JsonReplysList.class, response);
                            if (BaseActivity.handleResponseStatus(mContext, result)) {
                                Log.d(TAG, "评论回复 数据返回成功");
                                if (result.replyItems != null && result.replyItems.size() > 0) {
                                    item.addReplys(result.total, pageIndex, result.replyItems);
                                    adapter.notifyDataSetChanged();
                                }
                                refreshReplyListFoot(adapter, item, hold);
                            }
                        }

                        @Override
                        public void onEErrorResponse(VolleyError error) {
                            Toast.makeText(mContext, "错误：服务器返回数据失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onEFinish() {
                            super.onEFinish();
                            dismissProgressDialog();
                        }

                    });
                }
            });
        } else {
            hold.mTextReplyListFoot.setText("没有更多了");
            hold.mTextReplyListFoot.setOnClickListener(null);
        }
    }

    private void deleteComment(final int position, int commentId) {
        showProgressDialog();
        mRequest = APIForPoint.deleteComment(commentId, new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                JsonBase result = GsonUtils.toBean(JsonBase.class, response);
                if (BaseActivity.handleResponseStatus(mContext, result)) {
                    //删除成功后，刷新
                    mData.remove(position);
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onEErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "错误：服务器返回数据失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEFinish() {
                super.onEFinish();
                dismissProgressDialog();
            }

        });
    }

    private void showProgressDialog() {
        dismissProgressDialog();
        mProgressDialog = ProgressDialog.show(mContext, null, "提交中...", true, true, new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (mRequest != null) {
                    mRequest.cancel();
                }
            }
        });
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

}
